package com.zcdyy.rentalofhouse.ui.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;
import com.zcdyy.rentalofhouse.R;
import com.zcdyy.rentalofhouse.base.BaseFragment;
import com.zcdyy.rentalofhouse.bean.AllRental;
import com.zcdyy.rentalofhouse.bean.OrderInfo;
import com.zcdyy.rentalofhouse.bean.SaleHouse;
import com.zcdyy.rentalofhouse.bean.ShopRent;
import com.zcdyy.rentalofhouse.bean.SingleRent;
import com.zcdyy.rentalofhouse.constant.Constants;
import com.zcdyy.rentalofhouse.listener.OnItemClickListener;
import com.zcdyy.rentalofhouse.receiver.MyBroadCastReceiver;
import com.zcdyy.rentalofhouse.ui.activity.AllRentalDetailActivity;
import com.zcdyy.rentalofhouse.ui.activity.SaleHouseDetailActivity;
import com.zcdyy.rentalofhouse.ui.activity.ShopsDetailActivity;
import com.zcdyy.rentalofhouse.ui.activity.SingleDetailActivity;
import com.zcdyy.rentalofhouse.ui.adapter.RentalAdapter;
import com.zcdyy.rentalofhouse.utils.BmobUtils;
import com.zcdyy.rentalofhouse.utils.DividerItemDecoration;
import com.zcdyy.rentalofhouse.utils.RentalUtils;
import com.zcdyy.rentalofhouse.utils.Utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 首页
 * Created by chuan on 2017/3/9.
 */

public class MainFragment extends BaseFragment implements View.OnClickListener, OnItemClickListener {
    private static RentalAdapter adapter_static;
    private static List<OrderInfo> list = new ArrayList<>();
    private static ProgressDialog dialog;
    private static int selectId = 0;
    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (Constants.ResultCode.SUCCESS == msg.what){
                dialog.dismiss();
                addList(selectId);
            }
        }
    };
    private RelativeLayout back;
    private TextView title;
    private List<String> list_img = new ArrayList<>();
    private Banner banner;
    private RecyclerView recyclerView;
    private RentalAdapter adapter;
    private TextView[] tv_select = new TextView[4];
    private RelativeLayout[] rl_select = new RelativeLayout[4];
    private int[] tv_ids = {R.id.tv1, R.id.tv2, R.id.tv3, R.id.tv4};
    private int[] rl_ids = {R.id.rl1, R.id.rl2, R.id.rl3, R.id.rl4};
    private boolean[] select = {true, false, false, false};
    private Class[] cls = {AllRentalDetailActivity.class, SaleHouseDetailActivity.class
            , SingleDetailActivity.class, ShopsDetailActivity.class};
    private BmobUtils bmobUtils;
    private MyBroadCastReceiver receiver;
    private TextView refush;
    @Override
    protected View onCreateViews(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        findViewsByIds(view);
        initData();
        initBanner();
        bind();
        return view;
    }

    /**
     * 计算是否为半年前的发布，自动删除掉
     */
    public void caluter(OrderInfo orderInfo){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String now = format.format(new Date());
        Date now = null;
        Date pre = null;
        try {
            pre = format.parse(orderInfo.getCreatedAt());
            now = format.parse(format.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (now != null &&pre != null){
            long day = (now.getTime()-pre.getTime())/(24*60*60*1000);
            Log.e("day",day+"");
            if (day > 6*30){
                bmobUtils.deleteRental(orderInfo);
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        receiver = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter("download");
        getActivity().registerReceiver(receiver,filter);
        if (!BmobUtils.query){
            bmobUtils = new BmobUtils(getActivity());
            bmobUtils.queryOrderInfo();
            bmobUtils.queryAllRental();
            bmobUtils.querySaleHouse();
            bmobUtils.querySingleRent();
            bmobUtils.queryShopRent();
            BmobUtils.query = true;
            dialog = ProgressDialog.show(getActivity(), null, "正在获取数据...");
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(receiver);
    }

    private void initBanner() {
        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(list_img);
        banner.start();
    }

    private void initData() {
        title.setText("首页");
        back.setVisibility(View.GONE);
        list_img.add("http://pic1.58cdn.com.cn/anjuke_58/6761e8e9c8a2c405f84507d9731dc40d");
        list_img.add("http://pic2.58cdn.com.cn/anjuke_58/c5d0c72111dff5f66dcd82df0f89985e");
        list_img.add("http://pic7.58cdn.com.cn/anjuke_58/cd9f8d4259fedd2be581c8926ba91cff");
        list_img.add("http://pic5.58cdn.com.cn/anjuke_58/ea8b8bb97a2555dfa319511a6e8b999b");
        list_img.add("http://pic8.58cdn.com.cn/anjuke_58/dce28560dae567ae644ba062a1678402");
    }

    @Override
    public void onClick(View v) {
        for (int i = 0 ; i <tv_ids.length ; i++){
            if (v.getId() == tv_select[i].getId()||v.getId()==rl_select[i].getId()){
                if (!select[i]){
                    resetImg();
                    rl_select[i].setBackgroundResource(R.drawable.main_select_shape);
                    tv_select[i].setTextColor(getResources().getColor(R.color.colorWhite));
                    select[i] = true;
                    selectId = i;
                    addList(i);
                    break;
                }
            }
        }
    }

    private static void addList(int i) {
        List<OrderInfo> temp = new ArrayList<>();
        switch (i){
            case 0:
               for (OrderInfo o:RentalUtils.list_order){
                   if (o.getType().equals("0")){
                       temp.add(o);
                   }
               }
                break;
            case 1:
                for (OrderInfo o:RentalUtils.list_order){
                    if (o.getType().equals("1")){
                        temp.add(o);
                    }
                }
                break;
            case 2:
                for (OrderInfo o:RentalUtils.list_order){
                    if (o.getType().equals("2")){
                        temp.add(o);
                    }
                }
                break;
            case 3:
                for (OrderInfo o:RentalUtils.list_order){
                    if (o.getType().equals("3")){
                        temp.add(o);
                    }
                }
                break;
        }
        list.clear();
        list.addAll(temp);
        adapter_static.addList(list);
        adapter_static.notifyDataSetChanged();
    }

    public void resetImg(){
        for (int i = 0 ; i <tv_ids.length ; i++){
            rl_select[i].setBackgroundResource(R.drawable.main_unselect_shape);
            tv_select[i].setTextColor(getResources().getColor(R.color.colorBlack));
            select[i] = false;
        }
    }

    /**
     * 点击每个Item跳转不同的详情
     *
     * @param position
     */

    @Override
    public void onItemClick(int position) {
        switch (list.get(position).getType()){
            case "0"://整租

                for (AllRental a:RentalUtils.list_allRental){
                    if (a.getObjectId().equals(list.get(position).getTypeID())){
                        Intent intent = new Intent(getActivity(), cls[0]);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("allRental", a);
                        bundle.putString("title", "整租");
                        intent.putExtra("bundle", bundle);
                        startActivity(intent);
                        break;
                    }
                }
                break;
            case "1"://二手房
                for (SaleHouse s:RentalUtils.list_saleHouse){
                    if (s.getObjectId().equals(list.get(position).getTypeID())){
                        Intent intent = new Intent(getActivity(), cls[1]);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("allSale", s);
                        bundle.putString("title", "二手房");
                        intent.putExtra("bundle", bundle);
                        startActivity(intent);
                        break;
                    }
                }
                break;
            case "2"://单间
                for (SingleRent sr:RentalUtils.list_singleRent){
                    if (sr.getObjectId().equals(list.get(position).getTypeID())){
                        Intent intent = new Intent(getActivity(), cls[2]);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("single", sr);
                        bundle.putString("title", "单间");
                        intent.putExtra("bundle", bundle);
                        startActivity(intent);
                        break;
                    }
                }
                break;
            case "3"://商铺
                for (ShopRent sr:RentalUtils.list_shopRent){
                    if (sr.getObjectId().equals(list.get(position).getTypeID())){
                        Intent intent = new Intent(getActivity(), cls[3]);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("allshop", sr);
                        bundle.putString("title", "商铺");
                        intent.putExtra("bundle", bundle);
                        startActivity(intent);
                        break;
                    }
                }
                break;
        }
    }

    private void bind() {
        refush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    BmobUtils.queryCount = 0;
                    bmobUtils.queryOrderInfo();
                    bmobUtils.queryAllRental();
                    bmobUtils.querySaleHouse();
                    bmobUtils.querySingleRent();
                    bmobUtils.queryShopRent();
                    dialog = ProgressDialog.show(getActivity(), null, "正在获取数据...");

            }
        });
        adapter = new RentalAdapter(getActivity(),list);
        adapter_static = adapter;
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        DividerItemDecoration decoration = new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL_LIST);
        decoration.setDivider(R.drawable.divider_shape);
        recyclerView.addItemDecoration(decoration);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        for (int i = 0 ; i <tv_ids.length ; i++){
            tv_select[i].setOnClickListener(this);
        }
    }

    private void findViewsByIds(View view) {
        refush = Utils.findViewsById(view,R.id.top_tv_right);
        refush.setVisibility(View.VISIBLE);
        refush.setText("刷新");
        title = Utils.findViewsById(view,R.id.top_tv_title);
        back = Utils.findViewsById(view,R.id.top_rl_back);
        banner = Utils.findViewsById(view,R.id.banner);
        recyclerView = Utils.findViewsById(view,R.id.recycler);
        for (int i = 0 ; i <tv_ids.length ; i++){
            tv_select[i] = Utils.findViewsById(view,tv_ids[i]);
            rl_select[i] = Utils.findViewsById(view,rl_ids[i]);
        }
    }

    /**
     * 加载轮播图
     */
    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            /**
             注意：
             1.图片加载器由自己选择，这里不限制，只是提供几种使用方法
             2.返回的图片路径为Object类型，由于不能确定你到底使用的那种图片加载器，
             传输的到的是什么格式，那么这种就使用Object接收和返回，你只需要强转成你传输的类型就行，
             切记不要胡乱强转！
             */
            //Glide 加载图片简单用法
            Glide.with(context).load((String) path).error(R.drawable.default_icon).into(imageView);

        }
    }
}
